package com.jingyuan.client;

import com.jingyuan.common.entity.packet.OffLinePacket;
import com.jingyuan.common.entity.packet.RegistPacket;
import com.jingyuan.common.entity.packet.VotePacket;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

import java.util.concurrent.atomic.AtomicBoolean;

public class NettyHarmonyServiceImpl implements HarmonyService {
    private NettyHarmonyClient client;
    private PropertiesUtil propertyUtil;
    private AtomicBoolean isSetChannel=new AtomicBoolean(false);
    private Channel channel;

    public void setChannel(Channel channel){
        if(isSetChannel.compareAndSet(false,true)){
            this.channel=channel;
        }
    }
    @Override
    public void init() throws Exception {
        propertyUtil=PropertiesUtil.getPropertiesUtil();
        this.client=new NettyHarmonyClient(this);
        //在子线程中启动netty客户端
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.setServerAddress(propertyUtil.getServerAddress());
                client.setServerPort(propertyUtil.getServerPort());
                try {
                    client.start();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void online(RegistPacket registPacket) {
        ChannelFuture future = channel.writeAndFlush(registPacket);
        future.addListener(future1 -> {
            if(future1.isSuccess()){
                System.out.println("登录服务器成功");
                HeartBeatScheduleJob heartBeatScheduleJob=HeartBeatScheduleJob.getHearBeatScheduleJob();
                heartBeatScheduleJob.startSchedule(channel);
            }else {
                System.out.println("登录服务器失败");
            }
        });
    }

    @Override
    public void offline(OffLinePacket offLinePacket) {
        channel.writeAndFlush(offLinePacket);
        HeartBeatScheduleJob job=HeartBeatScheduleJob.getHearBeatScheduleJob();
        job.shutdown();     //停止发送心跳包
    }

    @Override
    public void vote(VotePacket votePacket) {
        channel.writeAndFlush(votePacket);
    }

    /**
     * 收到上线确认包
     */
    public void receiveRegistACK(){

    }
}
